<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title">
        <h3>车辆调度后台管理系统</h3>
      </div>
      <div>
        <el-tabs v-model="activeName">
          <el-tab-pane name="first">
            <template slot="label">
              <div class="login-nav">
                <i class="el-icon-user-solid"></i>
                <div style="margin-left: 10px">账号登录</div>
              </div>
            </template>
            <!-- 登录信息 -->
            <el-form style="margin-bottom: 25px;" :model="loginForm">
              <el-form-item>
                <el-autocomplete class="input_account" placeholder="请输入登录名" :fetch-suggestions="querySearch"
                  rigger-on-focus @select="selectAccount" v-model="loginForm.account">
                </el-autocomplete>
              </el-form-item>
              <el-form-item v-model="loginForm.password">
                <el-input :type="passwordType" v-model="loginForm.password" placeholder="请输入密码">
                  <i slot="suffix" :class="['el-icon-view', { 'el-icon-loading': passwordType === 'text' }]"
                    @click="togglePasswordVisibility"></i>
                </el-input>
              </el-form-item>
              <el-checkbox v-model="remember">记住我</el-checkbox>
              <div style="margin-top: 20px;">
                <el-button style="width: 336px;height: 35px;" type="primary" @click="loginHanler"
                  v-loading="loginLoading">登录</el-button>
              </div>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import { login } from '../../api/user/login.js';
export default {
  data() {
    return {
      passwordType: 'password',
      loginLoading: false,
      activeName: "first",
      remember: false,
      loginForm: {
        account: '',
        password: ''
      },
      recentAccounts: [] // 新增属性，用于存储历史记录
    }
  },
  created() {
    this.rememberedAccount = localStorage.getItem('rememberedAccount');
    this.recentAccounts = JSON.parse(localStorage.getItem("recentAccount")) || []
    if (this.rememberedAccount) {
      this.loginForm.account = this.rememberedAccount;
      this.remember = true; // 如果有记住的账户信息，默认勾选“记住我”
    }
    console.log(this.history, '历史数据');

  },
  methods: {
    async loginHanler() {
      this.loginLoading = true;
      try {
        let res = await login(this.loginForm);
        if (res.code == 0) {
          localStorage.setItem('token', res.data.token);
          this.$message({
            message: res.msg,
            type: 'success'
          });

          // 登录成功更新当前账户到历史记录
          this.updateRecentAccounts(this.loginForm.account, this.loginForm.password)
          if (this.remember) {
            localStorage.setItem('rememberedAccount', this.loginForm.account); // 保存账户信息
          } else {
            localStorage.removeItem('rememberedAccount'); // 删除账户信息
          }
          this.$router.push('/dashboard');
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
          this.loginLoading = false;
        }
      } catch (err) {
        console.log(err, 'ss');

        this.$message({
          message: '服务器错误',
          type: 'error'
        });
        this.loginLoading = false;
      }
    },
    togglePasswordVisibility() {
      this.passwordType = this.passwordType === 'password' ? 'text' : 'password';
    },

    querySearch(queryString, cb) {
      const accounts = this.recentAccounts.map(acc => acc.account);
      const results = queryString ? accounts.filter(this.createFilter(queryString)) : accounts;
      const data = results.map(function (item) {
        return { value: item };
      });
      cb(data);
    },
    createFilter(queryString) {
      return (account) => {
        return account.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    selectAccount(item) {
      this.loginForm.account = item.value
      const matchedAccount = this.recentAccounts.find(acc => acc.account === item.value)
      if (matchedAccount) {
        // this.loginForm.password = matchedAccount.password
        this.loginForm.password = matchedAccount.password
      } else {
        this.loginForm.password = ""
      }
    },
    handleSelect(item) {
      this.loginForm.account = item;
    },
    updateRecentAccounts(account, password) {
      // 移除已存在的相同账号
      this.recentAccounts = this.recentAccounts.filter(acc => acc.account !== account)
      // 添加新的账号到列表
      this.recentAccounts.unshift({ account, password });
      // 如果超过3个，则移除最后一个
      if (this.recentAccounts.length > 3) {
        this.recentAccounts.pop();
      }
      localStorage.setItem("recentAccount", JSON.stringify(this.recentAccounts))

    },

  }
}
</script>

<style lang='scss' scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  background: url('../../assets/images/login-back.jpg') no-repeat 100% 100%;
  background-size: cover;
}

.login-box {
  position: absolute;
  margin-top: -220px;
  top: 50%;
  left: 60%;
  border-radius: 5px;
  background-color: #fff;
  width: 385px;
  padding: 25px 25px 5px 25px;
  box-sizing: border-box;
}

.login-nav {
  width: 70px;
  height: 40px;
  display: flex;
  align-items: center;
}

:deep(.el-tabs__active-bar) {
  width: 85px !important;
}

.title {
  width: 335px;
  height: 21.5px;
  color: #707070;
  box-sizing: border-box;
  margin: 0 0 30px;
}

.input_account {
  width: 335px;

}
</style>